<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../layui/css/layui.css"  media="all">
</head>
<body>

  <div class="layui-fluid">
      <div class="layui-form">
        <div class="layui-inline">
             <label class="layui-form-label">等级筛选：</label>
              <div class="layui-input-block">
                <select name="interest" lay-filter="level" id="level">
                  <option value="2">A</option>
                  <option value="1">B</option>
                  <option value="0">C</option>
                  <option value="3">D</option>
                  <option value="4">E</option>
                  <option value="5">F</option>
                </select>
              </div>
        </div>
        <div class="layui-inline">
             <label class="layui-form-label">分配筛选：</label>
              <div class="layui-input-block">
                <select name="interest" lay-filter="fenpei" id="fenpei">
                  <option value="1">未分配</option>
                  <option value="0">已分配</option>
                  <option value="all">全部</option>
                </select>
              </div>
        </div>

        <div class="layui-inline">
          日期选择：
        </div>
        <div class="layui-inline">
          <input type="text" class="layui-input" id="date1" style="width:300px;">
        </div>
        <div class="layui-inline">
          <button class="layui-btn layui-btn-primary" id="importExcel">导出excel</button>
        </div>
        <div class="layui-inline">
          <button class="layui-btn layui-btn-sm layui-btn-disabled" id="distribution~" >分配</button>
        </div>
        <div class="layui-inline">
          <button class="layui-btn layui-btn-sm layui-btn-disabled" id="distributionAvg~">按需分配</button>
        </div>
      </div>
      <div class="layui-block">
        <table id="demo" lay-filter="test"></table>
      </div>
      
  </div>      
</body>
<script src="../layui/layui.all.js"></script>
<script type="text/javascript" src="../../disanfanglogin/vendor/jquery/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="../js/linxi.js?type=6"></script>
<script type="text/javascript">
  $(document).ready(function(){

    linxi.loginYanZheng(function(userInfo){

       

        if(userInfo.data.user_root.customer_pool==0){
            var layer = layui.layer;
            layer.msg('非法闯入')
            return;
        }



        var form = layui.form

        var table =  linxi.table;

        var layer = linxi.layer;

        

        linxi.createTable(
      
         {'type':'getDateAllMySql','starDate':linxi.starDate,'endDate':linxi.endDate,'userLevel':2,'fenpei':1}
         ,'#demo'
         ,[ //表头
             {field: '',title: '分配',type:'checkbox', fixed: 'left'}
            ,{field: '', title: '序号',  type: 'numbers', fixed: 'left'}
            ,{field: 'customerId', title: 'ID',  fixed: 'left'}
            ,{field: 'updatedAt', title: '最后处理时间',  sort: true, fixed: 'left'}
            ,{field: 'qudao', title: '渠道', }
            ,{field: 'mobile', title: '手机号'} 
          ]
          ,true)

        linxi.laydate('#date1',function(value, date, endDate){

            parmsObj=getlayerVals()
            parmsObj['starDate'] =value.split(' - ')[0]
            parmsObj['endDate'] = value.split(' - ')[1]

            table.reload('demo', {
              url: '../api/api.php' + linxi.createUrlParse(parmsObj)
            });
            

        })  //创建时间选择框

        // linxi.laySelect('level','demo',{'type':'getDateAllMySql'}) //创建ABC意向选择


        table.on('rowDouble(test)', function(obj){
            linxi.showRemark(obj)
        });

        // linxi.editCheckRowEvent('test')

        $('#importExcel').click(function(e){

            var parseData = {

                              type:'getDateAllMySql',
                              starDate:$('#date1').val().split(' - ')[0],
                              endDate:$('#date1').val().split(' - ')[1],
                              userLevel:$('#level').val(),

                            }


            $.get('../api/api.php',parseData,function(data){


                        var res = JSON.parse(data)
                        res['data'] = JSON.stringify(res['data'])
                        res['type']='importExcel'
                        res['tableName']='林西客资'
                        res['fields'] = [{field:'customerId',title:'ID'},{field:'updatedAt',title:'最后更新日期'},{field:'mobile',title:'手机号'},{field:'contactName',title:'客户姓名'},{field:'qudao',title:'渠道'}]
                        
                        $.post('../api/api.php',res,function(data){
                            
                            linxi.download_file(data)
                        })


            })

        })

        linxi.getTableCheck('#distribution','demo',function(checkStatus){

          linxi.selectKuFu(checkStatus)

        })

        $('#distributionAvg').click(function(e){ //按需分配

          $.get('../api/api.php' + linxi.createUrlParse(getlayerVals()),function(data){

              data = JSON.parse(data)

              var count = data.count
              // var count = parseInt(Math.random()*100)
              // var count = 0

              var list = data.data

              $.get('../api/api.php'+linxi.createUrlParse({type:'getYunWei'}),function(data){

                    var data = JSON.parse(data).data

                    // console.log(data)

                    var kefuCount=data.length;

                    $html=`
                          <div class="layui-fluid">
                            <div class="layui-row" style="height:100px; line-height:100px;text-align:center;">
                              <div class="layui-col-sm4">
                                <div class="layui-inline">待分配总数:</div>
                                <div class="layui-inline" id="daifenpeiCount">${count}</div>
                              </div>
                              <div class="layui-col-sm4">
                                <div class="layui-inline">未分配总数:</div>
                                <div class="layui-inline" id="weifenpeiCount">${count}</div>
                              </div>
                              <div class="layui-col-sm4">
                                <button class="layui-btn layui-btn-sm" id="avgFenPei">平均分配</button>
                              </div>
                            </div>
                            <div class="layui-row">
                              <div class="layui-col-sm12">
                                <table id="kefuFenPaiTable" lay-filter="kefuFenPaiTable"><table>
                              </div>
                            </div>
                          </div>
                    `

                    for(var i = 0 ;  i < data.length ; i++){

                        data[i]['number']=0
                    }

                    //页面层
                    var msgpage = layer.open({
                      type: 1,
                      // skin: 'layui-layer-rim', //加上边框
                      area: ['50%', '80%'], //宽高
                      content: $html,
                      title:'客资分配',
                      coloseBtn:0,
                      shadeClose:true,
                      btn:['提交'],
                      yes:function(index,layero){
                        
                        // console.log(data)
                        // console.log(list)

                        var ct = 0  //list 的计数器

                        for(var i = 0 ; i < data.length ; i++){

                          var kefuitem = data[i]

                          var number = kefuitem['number']

                          var customer_data = []

                          if(number>0){

                            for(var j = 0 ; j < number ; j++){

                              $.get('../api/api.php?type=insertCustomer_yunweinames&customerId='+list[ct]['customerId']+'&yunweiId='+kefuitem['userId']+'&updatetime='+linxi.nowDate,function(data){ //分配客服

                                data  = JSON.parse(data)
                                if(data.code == 300 ){
                                  console.log('分配成功')
                                }else if(data.code == 400){
                                  console.log('分配失败<br>失败原因：'+data.msg)
                                }

                              })

                              ct+=1

                            }

                          }

                          linxi.table.reload('demo');          

                        }


                      }
                    });


                    table.render({  //创建分配表格
                         elem: '#kefuFenPaiTable'
                        ,data: data //数据接口
                        ,page: false //开启分页
                        ,cols: [[ //表头
                           ,{field: 'name', title: '客服姓名', align: 'center'}
                           ,{field: '', title: '',align: 'center',templet:"#add", align: 'center'}
                          ,{field: 'number', title: '数量',edit:true, align: 'center'}
                          ,{field: '', title: '',align: 'center',templet:"#subtrac", align: 'center'}
                          ,{field: '', title: '',align: 'center',templet:"#del", align: 'center'}
                        ]]

                      
                    })


                    $("#avgFenPei").click(function(e){ //平均分配的功能
                      
                      kefuCount=data.length;

                      var mod = count % kefuCount

                      var avg = count / kefuCount

                      // console.log('mod=>',mod)

                      for(var i = 0 ; i < kefuCount ; i++){
                        
                        data[i]['number'] = parseInt(avg);
                      }

                      for(var j = 0 ; j < mod ; j++){
                        data[j]['number'] += 1;
                      }

                      table.reload('kefuFenPaiTable',{
                        data:data
                      })

                      $('#weifenpeiCount').text(0)

                    })

                    table.on('edit(kefuFenPaiTable)', function(obj){ //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
                      
                      // console.log(obj.value); //得到修改后的值
                      // console.log(obj.field); //当前编辑的字段名
                      // console.log(obj.data); //所在行的所有相关数据
                      // console.log($(obj.tr))

                      var dataIndex = $(obj.tr[0]).data()['index']

                      var num = 0

                      for(var i = 0; i < data.length; i ++){
                        if(i==dataIndex){
                          num+=parseInt(obj.value)
                        }else{
                          num+=parseInt(data[i]['number'])
                        }  
                      }

                      if($('#daifenpeiCount').text() - num < 0){

                        layer.msg('没有这么多可分配客资')

                        // console.log(data)

                        table.reload('kefuFenPaiTable',{data:data})

                        return
                      }

                      data[dataIndex]['number'] = parseInt(obj.value)
                      
                      table.reload('kefuFenPaiTable',{data:data})
                     
                      $('#weifenpeiCount').text($('#daifenpeiCount').text() - num)

                    });


                    //工具条事件
                    table.on('tool(kefuFenPaiTable)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                      // var data = obj.data; //获得当前行数据
                      var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                      var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
                      
                      var dataIndex = $(obj.tr[0]).data()['index']
                      console.log(dataIndex)
                      if(layEvent === 'del'){ //删除

                        obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                        data.splice(dataIndex,1)


                      } else if(layEvent === 'add'){ //编辑

                        var num = 0

                        for(var i = 0; i < data.length; i ++){
                          
                          if(i==dataIndex){
                            num=1+data[i]['number']
                          }else{
                            num+=parseInt(data[i]['number'])
                          }  
                        }

                        if($('#daifenpeiCount').text() - num < 0){

                          layer.msg('没有这么多可分配客资')

                          console.log(data)

                          table.reload('kefuFenPaiTable',{data:data})

                          return
                        }


                        data[dataIndex]['number']+=1


                        
                      } else if(layEvent === 'subtrac'){

                        data[dataIndex]['number']-1>=0?data[dataIndex]['number']-=1:''
     
                      }

                      // console.log(data)

                      table.reload('kefuFenPaiTable',{data:data})

                    });






              })

          })
 


        })




        form.on('select(fenpei)',function(data){
          
          table.reload('demo', {
              url: '../api/api.php' + linxi.createUrlParse(getlayerVals())
          });

        })

        form.on('select(level)',function(data){
          table.reload('demo', {
              url: '../api/api.php' + linxi.createUrlParse(getlayerVals())
          });
        })


        function getlayerVals(){

          var parmsObj={}
          parmsObj['type']='getDateAllMySql'
          parmsObj['starDate'] =$('#date1').val().split(' - ')[0]
          parmsObj['endDate'] = $('#date1').val().split(' - ')[1]
          parmsObj['userLevel'] = $('#level').val()
          parmsObj['fenpei'] = $('#fenpei').val()
          
          return parmsObj

        }



    })

    


  })
</script>
</html>
<script type="text/html" id="del">
  <i class="layui-icon layui-icon-delete iconbth" style="font-size: 30px; color: #1E9FFF;" lay-event="del"></i>
</script>
<script type="text/html" id="add">
  <i class="layui-icon layui-icon-addition iconbth" style="font-size: 10px; color: #1E9FFF;" lay-event="add"></i>
</script>
<script type="text/html" id="subtrac">
  <i class="layui-icon layui-icon-subtraction iconbth" style="font-size: 10px; color: #1E9FFF;" lay-event="subtrac"></i>
</script>
